package com.xx.springboot.DataStructure.Queue;


/**
 * 构造循环队列
 *
 * @param <T>
 */
public class TestLoopQueue<T> implements Queue<T> {

    private T[] data;
    private int size;
    private int front, tail;

    public TestLoopQueue(int capacity){
        data = (T[]) new Object[capacity];
        size = 0;
        front = 0;
        tail = 0;
    }

    public TestLoopQueue(){
        this(10);
    }

    public int getCapacity(){
        return data.length - 1;
    }

    /**
     * 队列的长度
     *
     * @return
     */
    public int getSize() {
        return size;
    }

    /**
     * 队列是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return front == tail;
    }

    /**
     * 得到队列的第一个元素
     *
     * @return
     */
    public T getFront() {
        if (isEmpty())
            throw new IllegalArgumentException("Queue is null");

        return data[front];
    }

    /**
     * 入队操作
     *
     * @param t
     */
    public void enqueue(T t) {

        if((tail + 1) % data.length == front)
            resize(2 * getCapacity());

        data[tail] = t;
        tail = (tail + 1) % data.length;
        size ++;
    }

    /**
     * 出队操作
     *
     * @return
     */
    public T dequeue() {
        if (isEmpty())
            throw new IllegalArgumentException("cannot dequeue from an empty queue");

        T res = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size --;

        if (size == getCapacity() / 4 && getCapacity() / 2 != 0 )
            resize(getCapacity() / 2);
        return res;
    }

    private void resize(int newCapacity){
        T[] newData = (T[]) new Object[newCapacity];
        for (int i = 0; i < data.length; i++) {
            newData[i] = data[(front + i) % data.length];
        }
        data = newData;
        front = 0;
        tail = size;
    }

    @Override
    public String toString(){
        StringBuffer res = new StringBuffer();
        res.append("front [");
        for (int i = front; i != tail; i = (i + 1) % data.length) {
            res.append(data[i]);
            if ((i + 1) % data.length != tail)
                res.append(", ");
        }
        res.append("]");
        return res.toString();
    }

    public static void main(String[] args) {
        TestLoopQueue<Integer> test = new TestLoopQueue<Integer>();
        for (int i = 0; i < 10; i++) {
            test.enqueue(i);
            System.out.println(test);
        }
    }
}
